package com.tansun.easycare.rule.ruletest.web;
/**
 * Created by Chenbaichuan on 2017/9/19 11:32
 **/

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.tansun.easycare.rule.common.JsonMessage;
import com.tansun.easycare.rule.common.ResMessage;
import com.tansun.easycare.rule.common.RuleBaseController;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.ruleflow.service.RuleFlowService;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.model.RuleManageVO;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.easycare.rule.ruletest.entity.RuleReq;
import com.tansun.easycare.rule.ruletest.entity.RuleTest;
import com.tansun.easycare.rule.ruletest.entity.RuleTestdata;
import com.tansun.easycare.rule.ruletest.service.ContrastTestService;
import com.tansun.easycare.rule.ruletest.service.RuleResponseService;
import com.tansun.easycare.rule.ruletest.service.RuleTestService;
import com.tansun.easycare.rule.ruletest.service.RuleTestdataService;
import com.tansun.easycare.rule.ruleversion.entity.RuleVersioninfo;
import com.tansun.easycare.rule.ruleversion.service.RuleVersioninfoService;
import com.tansun.rule.common.RuleModelTypeEnum;
import com.tansun.rule.redis.RedisService;

/**
 * @author chenbaichuan
 * @className ContrastTestController
 * @desc
 * @created 2017/9/19 11:32
 * @modified by 2017-9-29 14:08:18
 **/
@Controller
@RequestMapping(value = "/ruleProj/contrastTest")
public class ContrastTestController extends RuleBaseController {
    @Autowired
    public RuleManageService ruleManageService;
    @Autowired
    RuleVersioninfoService ruleVersioninfoService;
    @Autowired
    ContrastTestService contrastTestService;
    @Autowired
    RuleTestService ruleTestService;
    @Autowired
    RuleResponseService ruleResponseService;
    @Autowired
    RuleFlowService ruleFlowService;
    @Autowired
    RuleTestdataService ruleTestdataService;
    /**
     * 对比测试列表信息
     */
    @RequestMapping(value = "index")
    public String index(HttpServletRequest request, HttpServletResponse response, RuleTest ruleTest, ModelMap map) throws Exception {
        ruleTest.setTestType("2");//对比测试
        PageInfo<RuleTest> page = this.ruleTestService.findPage(ruleTest.getPage(), ruleTest);
        map.put("page", page);
        RuleManage param = new RuleManage();
        param.setProjectCode(this.getCurrProjectCode());
        param.setModelType(RuleModelTypeEnum.RuleFlow.getCode());
        List<RuleManage> ruleFlows = ruleManageService.findList(param);
        map.put("ruleFlows", ruleFlows);
        map.addAttribute("projectCode", getCurrProjectCode());
        return "rule/contrastTest/contrastTestIndex";
    }
    /**
     * 对比测试删除
     *
     * @param id 测试id
     */
    @RequestMapping(value = "delete")
    public @ResponseBody ResMessage delete(String id) throws Exception {
        ResMessage message = new ResMessage();
        try {
            ruleTestService.delRuleTest(id);
            message.setCode("success");
            message.setMsg("删除成功");
        } catch (Exception e) {
            message.setCode("fail");
            message.setMsg("删除失败");
        }
        return message;
    }
    /**
     * 测试规则页面
     *
     * @param id 对比测试ID
     */
    @RequestMapping(value = "testDataList")
    public String testDataList(HttpServletRequest request, HttpServletResponse response,RuleTestdata param, ModelMap map) throws Exception {
    	RuleTest testModel = this.ruleTestService.get(param.getRelationId());
        PageInfo<RuleTestdata> page = this.ruleTestdataService.findPage(param.getPage(), param);
        map.put("projectCode", this.getCurrProjectCode());
        map.put("testModel", testModel);
        map.put("page", page);
        return "rule/contrastTest/testDataList";
    }
    @RequestMapping(value = "testData")
    public String testData(String id,ModelMap map) throws Exception {
    	RuleTestdata testData = this.ruleTestdataService.get(id);
    	RuleTest testModel = this.ruleTestService.get(testData.getRelationId());
    	map.put("testModel", testModel);
        map.put("testData", testData);
        return "rule/contrastTest/testData";
    }
    

    @RequestMapping("saveOrUpdate")
    public @ResponseBody JsonMessage savaOrUpdate(RuleTest ruleTest) throws Exception {
    	JsonMessage message = new JsonMessage();
        try {
        	ruleTest.setTestType("2");
            ruleTest.setProjectCode(getCurrProjectCode());
            contrastTestService.saveOrUpdate(ruleTest);
        } catch (BizException e) {
            e.printStackTrace();
            message.setResult(false);
            message.setMessage(e.getMessage());
        }
        return message;
    }
    /**
     * ruletestAction
     *
     * @param id                测试ID
     * @param testName          测试名称
     * @param ruleFlowId        测试规则流ID
     * @param ruleFlowVersion   测试数据版本
     * @param testExcuteVersion 执行测试版本
     */
    @RequestMapping("saveTestData")
    public @ResponseBody JsonMessage saveTestData(@RequestBody RuleTestdata testData) throws Exception {
        JsonMessage message = new JsonMessage();
        try {
        	this.ruleTestdataService.save(testData);
        } catch (Exception e) {
            e.printStackTrace();
            message.setResult(false);
            message.setMessage(e.getMessage());
        }
        return message;
    }
    @RequestMapping("deleteTestData")
    public @ResponseBody JsonMessage deleteTestData(String id) throws Exception {
        JsonMessage message = new JsonMessage();
        try {
        	RuleTestdata condition = new RuleTestdata(id);
        	this.ruleTestdataService.delete(condition);
        } catch (Exception e) {
            e.printStackTrace();
            message.setResult(false);
            message.setMessage(e.getMessage());
        }
        return message;
    }
    
    @RequestMapping("testDataAnalysis")
    public String testDataAnalysis(String testModelId) throws Exception {
    	 return "rule/contrastTest/testDataAnalysis";
    }
    /**
     * 获取所有规则流模型
     */
    @RequestMapping(value = "getRuleFlow")
    public @ResponseBody List<RuleManageVO> getRuleFlow() throws Exception {
        RuleManageVO ruleManageVO = new RuleManageVO();
        ruleManageVO.setModelType(RuleModelTypeEnum.RuleFlow.getCode());
        ruleManageVO.setProjectCode(getCurrProjectCode());
        return ruleManageService.findRuleManageVO(ruleManageVO);
    }

    /**
     * 获取模型所有版本信息
     *
     * @param id 规则流id
     */
    @RequestMapping(value = "getModelVersion")
    public @ResponseBody
    List<RuleVersioninfo> getModelVersion(String id) throws Exception {
        RuleVersioninfo info = new RuleVersioninfo();
        info.setManageId(id);
        info.setModelType(RuleModelTypeEnum.RuleFlow.getCode());
        return ruleVersioninfoService.findPublishVersionList(info);
    }

	@Autowired
	private RedisService redisService;
    /**
     * 执行测试
     */
    @RequestMapping(value = "excuteTest")
    public @ResponseBody JsonMessage excuteTest(String testModelId) throws Exception {
        JsonMessage jsonMessage = new JsonMessage();
        try {
            int count = contrastTestService.excuteTest(testModelId);
            jsonMessage.setMessage("执行成功："+count);
        } catch (Exception e) {
        	e.printStackTrace();
            jsonMessage.setResult(false);
            jsonMessage.setMessage("执行失败");
        }
        return jsonMessage;
    }

    /**
     * 导入excel
     * @param file
     */
    @RequestMapping("upload")
    public void importExcel(@RequestParam("file") MultipartFile file,HttpServletRequest request, HttpServletResponse res) throws Exception {
        res.setHeader("Content-Type", "text/html;charset=UTF-8");
        res.setCharacterEncoding("UTF-8");
        PrintWriter pw = res.getWriter();
        ResMessage msg = null;
        try {
            Workbook workbook = null;
            // 判断上传文件类型
            if (file.getOriginalFilename().toLowerCase().endsWith("xlsx")) {
                workbook = new XSSFWorkbook(file.getInputStream());
            } else if (file.getOriginalFilename().toLowerCase().endsWith("xls")) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else {
                msg = new ResMessage("failure", "文件不是Excel格式");
            }
            if (workbook != null) {
            	Sheet sheet = workbook.getSheetAt(0);
            	List<RuleReq> reqList = new ArrayList<RuleReq>();
            	for(int i=0;i<=sheet.getLastRowNum();i++) {
            		if(i==0)
            			continue;
            		Row row = sheet.getRow(i);
            		RuleReq ruleReq = new RuleReq();
            		ruleReq.setProjectCode(row.getCell(0).toString());
            		ruleReq.setRuleFlowCode(row.getCell(1).toString());
            		ruleReq.setRuleFlowVersion(row.getCell(2).toString());
            		ruleReq.setEntryPoint(row.getCell(3).toString());
            		ruleReq.setOccurTime(row.getCell(4).toString());
            		ruleReq.setSerialNo(row.getCell(5).toString());
            		ruleReq.setTxParameter(row.getCell(6).toString());
            		reqList.add(ruleReq);
            	}
//            	ruleRequestService.insertBatch(reqList);
                msg = new ResMessage("success", "上传成功");
            } else {
                msg = new ResMessage("failure", "上传失败");
            }
        } catch (Exception e) {
            msg = new ResMessage("failure", "上传失败" + e);
            e.printStackTrace();
        }
        pw.write(JSONArray.toJSONString(msg));
        pw.flush();
        pw.close();
    }
}